<template>



  <div>

    <el-container  class ='set-aside' >

      <el-aside width="200px"  class="set-eltree-textsize">

        <!--<span class="inputstyle"> <el-input v-model="filtertext"></el-input></span>-->
        <!--<el-tree :data="projects" :props="defaultProps"   :highlight-current=true  :expand-on-click-node=false node-key="id"-->
        <!--@current-change="getCurrentProjectDto"-->
        <!--:filter-node-method="filterNode"-->
        <!--ref="projectTree"-->
        <!--&gt;-->

        <!--</el-tree>-->
        <projectTree @project-change = 'projectChange'  ref="project"></projectTree>


      </el-aside>

      <el-main>

        <!--<el-upload-->
          <!--class="upload-demo"-->
          <!--:action="uploadScriptsUrl"-->

          <!--:on-success="onsuccess"-->
          <!--multiple-->

        <!--&gt;-->
          <!--<el-button size="small" type="primary" accept=".myjson" @change="uploadScripte" id="file_executor">上传用例</el-button>-->
          <!--<div slot="tip" class="el-upload__tip">只能上传myjson文件</div>-->

        <!--</el-upload>-->


        <!--<el-button  @click="downLoadFile"  icon="el-icon-download" type="primary">下载用例</el-button>-->
        <batchTaskCreate :dbs="dbs" :scripts="downloadScripts" ref="bathctaskcreate"></batchTaskCreate>

        <el-button  @click="downloadSelectedScript"  icon="el-icon-download" type="primary">下载选中的</el-button>

        <input type="file" ref="upload" accept=".myjson" @change="uploadScripte" id="file_executor" class="outputlist_upload"  :disabled="uploadflag">
        <br>

        <el-button type="text" @click="showbatchtask"  ref="button">批量创建任务</el-button>
        <el-button type="text" @click="newscriptinit"  ref="button">新增用例</el-button>

        <el-dialog title="新增用例" :visible.sync="newScriptFlag">
          <el-form :model="newScriptDto"  refs="dbForm" >

            <el-form-item label="目录" :label-width="formLabelWidth">


              <el-input  v-model="selectedPro.name"  :disabled="true"></el-input>

            </el-form-item>

            <el-form-item label="名称" :label-width="formLabelWidth">

              <!--<selectTool :options="cwtype" label="name" @selectedindex="getzipZLBSXLindex"  style="display: inline-block"></selectTool><-->
              <el-input v-model="newScriptDto.name" autocomplete="off"></el-input>



            </el-form-item>

            <el-form-item label="功能点" :label-width="formLabelWidth">

              <!--<selectTool :options="cwtype" label="name" @selectedindex="getzipZLBSXLindex"  style="display: inline-block"></selectTool><-->
              <el-input v-model="newScriptDto.mouduleName" autocomplete="off"></el-input>

            </el-form-item>

            <el-form-item label="用例说明" :label-width="formLabelWidth" >


              <el-input style="width: 100%" v-model="newScriptDto.comment" autocomplete="off"   type="textarea" :rows="3"></el-input>

            </el-form-item>



            <el-form-item label="源sql" :label-width="formLabelWidth" >

              <el-input  style="width: 100%"  v-model="newScriptDto.srcSql" autocomplete="off"   type="textarea" :rows="3" ></el-input>


            </el-form-item>
            <el-form-item label="目标sql" :label-width="formLabelWidth" >


              <el-input style="width: 100%" v-model="newScriptDto.destSql" autocomplete="off"   type="textarea" :rows="3"></el-input>

            </el-form-item>
            <el-form-item label="变量" :label-width="formLabelWidth">


              <mytag :tags="newScriptDto.variables" :type="2"></mytag>
            </el-form-item>


            <el-form-item label="主键" :label-width="formLabelWidth">

              <mytag :tags="newScriptDto.authors" :type="1"></mytag>

            </el-form-item>



          </el-form>
          <div slot="footer" class="dialog-footer">

            <el-button @click="newScriptFlag = false">取 消</el-button>

            <el-button type="primary" @click="createNewScript">确 定</el-button>
          </div>
        </el-dialog>



        <el-dialog title="修改脚本" :visible.sync="updateScriptFlag">
          <el-form :model="updateScriptDto"  refs="dbForm" >

            <el-form-item label="所属项目" :label-width="formLabelWidth">


              <el-input  v-model="selectedPro.name"  :disabled="true"></el-input>

            </el-form-item>

            <el-form-item label="名称" :label-width="formLabelWidth">

              <!--<selectTool :options="cwtype" label="name" @selectedindex="getzipZLBSXLindex"  style="display: inline-block"></selectTool><-->
              <el-input v-model="updateScriptDto.name" autocomplete="off" ></el-input>

            </el-form-item>


            <el-form-item label="源sql" :label-width="formLabelWidth">
              <el-input v-model="updateScriptDto.srcSql" autocomplete="off" type="textarea" :rows="3"></el-input>
            </el-form-item>

            <el-form-item label="目标sql" :label-width="formLabelWidth">
              <el-input v-model="updateScriptDto.destSql" autocomplete="off"  type="textarea" :rows="3"></el-input>
            </el-form-item>

            <el-form-item label="变量" :label-width="formLabelWidth">


              <mytag :tags="updateScriptDto.variables" :type="2"></mytag>
            </el-form-item>


            <el-form-item label="主键" :label-width="formLabelWidth">

              <mytag :tags="updateScriptDto.authors" :type="1"></mytag>

            </el-form-item>



          </el-form>
          <div slot="footer" class="dialog-footer">

            <el-button @click="updateScriptFlag = false">取 消</el-button>

            <el-button type="primary" @click="updateScript">确 定</el-button>
          </div>
        </el-dialog>



        <div>

          <!--<selectTool :options="projects" label="name"  @selectedindex="getProjectIndex"></selectTool>-->
          <el-form :inline="true" :model="searchScriptDto" class="demo-form-inline">
            <el-form-item label="项目名">
              <el-input  v-model="selectedPro.name"  :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="用例名">
              <el-input v-model="searchScriptDto.scriptName" placeholder="数据库名"></el-input>
            </el-form-item>
            <el-form-item label="模块">
              <el-input v-model="searchScriptDto.mouduleName" placeholder="数据库名"></el-input>
            </el-form-item>
            <el-form-item label="创建人">
              <el-input v-model="searchScriptDto.createBy" placeholder="数据库名"></el-input>
            </el-form-item>


            <el-form-item>
              <el-button type="primary" @click="searchSubmit">查询</el-button>
              <el-button type="primary" @click="resetSearch">清空</el-button>
            </el-form-item>
          </el-form>

        </div>


        <div class="setbutton">
          <el-table :data="scriptsDtos"  @selection-change="selectChange">
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>

            <el-table-column
              prop="name"
              label="名称"
            ></el-table-column> <el-table-column
              prop="mouduleName"
              label="模块"
            ></el-table-column>

            <el-table-column
              prop="srcSql"
              label="源sql"
            ></el-table-column>

            <el-table-column
              prop="destSql"
              label="目标sql"
            ></el-table-column>

            <el-table-column
              prop="createBy"
              label="创建人"
            ></el-table-column>
            <el-table-column
              prop="date"
              label="创建时间"
            ></el-table-column>


            <el-table-column label="confirm" >
              <template slot-scope="{row,index}">


                <el-button type="primary" size="mini" @click="createTaskInit(row,index)" >生成任务</el-button>
                <el-button type="primary" size="mini" @click="updateFlag(row,index)" >修改用例</el-button>
                <el-button type="primary" size="mini" @click="deleteScript(row,index)" >删除用例</el-button>
              </template>
            </el-table-column>


          </el-table>

        </div>

        <div class="block">

          <el-pagination
            @size-change="pageSizeChange"
            @current-change="pageCurrentChange"
            :current-page="searchScriptDto.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="searchScriptDto.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
          </el-pagination>
        </div>



        <el-dialog title="新增任务" :visible.sync="createTaskFlag">
          <el-form :model="newTaskDto"  refs="dbForm" >


            <el-form-item label="名称" :label-width="formLabelWidth">

              <!--<selectTool :options="cwtype" label="name" @selectedindex="getzipZLBSXLindex"  style="display: inline-block"></selectTool><-->
              <el-input v-model="newTaskDto.name" autocomplete="off"></el-input>

            </el-form-item>


            <el-form-item label="源数据库" :label-width="formLabelWidth">
              <selectTool :options="dbs" label="dbname"  ref="selectTool1"  @selectedindex="getSrcDbid"></selectTool>
            </el-form-item>

            <el-form-item label="目标数据库" :label-width="formLabelWidth">
              <selectTool :options="dbs" label="dbname"   ref="selectTool2"  @selectedindex="getDestDbid"></selectTool>
            </el-form-item>

            <el-form-item label="变量值设置" :label-width="formLabelWidth">
              <ul v-for="i in newTaskDto.variables">
                <li> {{i.varName}}: <el-input v-model="i.value" style="width: 75%"></el-input></li>

              </ul>

            </el-form-item>


          </el-form>
          <div slot="footer" class="dialog-footer">

            <el-button type="primary" @click="createNewTaskTemp">试运行</el-button>
            <el-button @click="createTaskFlag = false">取 消</el-button>

            <el-button type="primary" @click="createNewTask">确 定</el-button>

          </div>
        </el-dialog>


      </el-main>
    </el-container>











  </div>

</template>

<script>
  import batchTaskCreate from './component/batchTaskCretae'
  import projectTree from './component/projectTree'
  import mytag from './component/tagsSet'
  import selectTool from '../shuiyoutools/components/selectTool'
  import {getProject,getsqlCompareScript,savesqlCompareScript,updatesqlCompareScript,
    uploadsqlCompareScripts,getalldbs,getdbByProjectId,saveSqlCompareTask,downloadallinfos,uploadScript,deleteScript} from '../../api/shuzhiCompare'
  import $ from 'jquery'
    export default {
        name: "scripts",
        data(){
          return{
            batchtaskcreateflag:false,
            uploadflag:true,
            createTaskFlag:false,
            formLabelWidth:'150px',
            newScriptFlag:false,
            updateScriptFlag:false,
            newScriptDto:{
              id:0,
              projectid:0,
              name:'',
              srcSql:'',
              destSql:'',
              authors:[],
              status:1,
              mouduleName:'',
              comment:'',
              variables:[],
              type:''

            },
            updateScriptDto:{
              id:0,
              projectid:0,
              name:'',
              srcSql:'',
              destSql:'',
              authors:[],
              status:1,
              mouduleName:'',
              comment:'',
              variables:[],
              type:''
            },
            projects:[],
            searchScriptDto:{
              pageNum:1,
              pageSize:10,
              projectId:0,
              scriptName:'',
              mouduleName:'',
              createBy:''

            },
            scriptsDtos:[],
            page:{},
            newTaskDto:{
              id:0,
              name:'',
              project:{},
              script:{},
              variables:[],
              srcDb:{},
              destDb:{},
              autoflag:0,
              status:1
            },
            dbs:[],
            uploadScriptsUrl:'',
            selectedPro:{},
            downloadScripts:[],
            uploadfileTest:[]
          }
        },
      methods:{

        deleteScript(row){

          this.deltetescriptno = row.scriptno
          let that = this
          this.$confirm('此操作将永久删除该用例, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteScript(row.scriptno).then(res=>{
              that.getScripts()
            })

            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });

        },

        showbatchtask(){
          console.log(this.$refs)
          this.$refs.bathctaskcreate.batchTaskflag = true
          this.$refs.bathctaskcreate.initBatchTask()
        },

      async  uploadScripte(){
        let that = this
          var files = $('#file_executor').prop('files')
          var reader = new FileReader();//新建一个FileReader
          reader.readAsText(files[0], "UTF-8");//读取文件
        reader.onload = await function(evt) { //读取完文件之后会回来这里
            let string = evt.target.result; // 读取文件内容
              let josn  = JSON.parse(string)
            console.log(josn)
         uploadScript(that.selectedPro.id,josn)

          }
          console.log(files)
        },

        selectChange(value){
          this.downloadScripts = value
          console.log(value)
        },


        downLoadFile(){

          let param = {
            fileName : "dfdf"
          }
          downloadallinfos(param)
            .then(rep=>{
              console.log(rep)
              let fileName= "121212.zip"
              let aTag = document.createElement('a');
              let blob = new Blob([rep.data]);　　// 这个content是下载的文件内容，自己修改
              aTag.download = "exs.xls";　　　　　　// 下载的文件名
              aTag.href = URL.createObjectURL(blob)

              aTag.click();
              URL.revokeObjectURL(blob)
            })


        },
        downloadSelectedScript(){

          let content = JSON.stringify(this.downloadScripts)
          let fileName= 'scripts.myjson'
          let aTag = document.createElement('a');
          let blob = new Blob([content]);　　// 这个content是下载的文件内容，自己修改
          aTag.download = fileName;　　　　　　// 下载的文件名
          aTag.href = URL.createObjectURL(blob)

          aTag.click();
          URL.revokeObjectURL(blob)

        },
        newscriptinit(){
          if (!this.selectedPro.id){
            this.warn("请先选择目录")
            return
          }
          this.newScriptFlag = true
          this. newScriptDto={
            id:0,
              projectid:this.selectedPro.id,
              name:'',
              srcSql:'',
              destSql:'',
              authors:[],
              status:1,
              mouduleName:'',
              comment:'',
              variables:[],
              type:''

          }

        },

        onsuccess(rep){
          this.$notify({
            title: '提示',
            message: rep,

          });
          this.getScripts()
        },

        projectChange(selectedPro){
          this.selectedPro = selectedPro
          this.newTaskDto.projectId = selectedPro.id
          this.searchScriptDto.projectId = selectedPro.id
          this.newScriptDto.projectid = selectedPro.id
this.uploadflag = false
          this.getScripts()
        },

        getUploadUrl(){
          this.uploadScriptsUrl = uploadsqlCompareScripts()
        },

        getSrcDbid(index){
          this.newTaskDto.srcDb = this.dbs[index]

        },
        getDestDbid(index){
          this.newTaskDto.destDb = this.dbs[index]
        },

       async createTaskInit(row){

         // if (!this.selectedPro.id){
         //   this.warn("请先选择目录")
         //   return
         // }

         let newTaskDto = {
           id:0,
           name:'',
           project:{},
           script:{},
           variables:[],
           srcDb:{},
           destDb:{},
           autoflag:0,
           status:1,
           scriptName:row.name
         }



         this.newTaskDto = newTaskDto



          this.newTaskDto.project = this.selectedPro
          this.newTaskDto.script = row


         for (let i in row.variables){
           let newTaskVariable={
             id:0,
             varName:'',
             value:'',
             taskId:0
           }

           newTaskVariable.varName = row.variables[i].name
           console.log('taskdto variables')
           console.log(i)
           console.log(newTaskVariable)
           this.newTaskDto.variables.push(newTaskVariable)
         }

         console.log(this.$refs)
        await  this.getDbs(row.projectid)
          this.createTaskFlag = true
        this.$mount()
         console.log(this.$refs)
         this.$refs.selectTool2.value = ''
        this.$refs.selectTool1.value = ''




        },
        createNewTask(){
          let that = this
          saveSqlCompareTask(this.newTaskDto).then(res=>{
            that.createTaskFlag = false
            this.$store.dispatch("setSelectedTaskId",res.data.id)
            this.$router.push("/sycompare/result")
          }).catch(err=>{
            that.warn(err.data())
          })
        },
        createNewTaskTemp(){

          let that = this
          saveSqlCompareTask(this.newTaskDto).then(res=>{
            that.createTaskFlag = false
            this.$store.dispatch("setSelectedTaskId",res.data.id)
            this.$store.dispatch("setTempTaskFlag",true)
            this.$store.dispatch("setTempTaskNo",res.data.taskno)
            this.$router.push("/sycompare/result")
          }).catch(err=>{
            that.warn(err.data())
          })
        },





        getDbs(projectId){
          let that = this
          getalldbs().then(res=>{
            that.dbs = res.data
          })
        },

        pageSizeChange(size){
          this.searchScriptDto.pageSize = size
          this.getScripts()
        },
        pageCurrentChange(page){
          this.searchScriptDto.pageNum = page
          this.getScripts()
        },

        updateFlag(row,index){
          this.updateScriptFlag = true
          this.updateScriptDto = row
        },

        searchSubmit(){
          this.getScripts()
        },
        resetSearch(){
          this.searchScriptDto.projectId=0
          this.searchScriptDto.createBy=''
          this.searchScriptDto.scriptName=''
          this.searchScriptDto.mouduleName=''
          this.selectedPro={}
        },


        setSearchProjectid(index){
          this.searchScriptDto.projectId = this.projects[index].id
        },

        getProjectIndexNew(index){
          this.newScriptDto.projectid = this.projects[index].id
        },

        getProjectIndexUpdate(index){
          this.updateScriptDto.projectid = this.projects[index].id
        },
        createNewScript(){
          console.log('this.selectedPro.id')
          console.log(this.selectedPro.id)
          if (!this.selectedPro.id){
            this.warn("请先选择目录")
            return
          }
          let that = this
          savesqlCompareScript(this.newScriptDto).then(res=>{
              that.newScriptFlag=false
            that.getScripts()
          }).catch(err=>{
            this.warn(err.data)
          })
        },
        updateScript(){
          let that = this
          updatesqlCompareScript(this.updateScriptDto).then(res=>{
            that.updateScriptFlag=false
            that.getScripts()
          }).catch(err=>{
            this.warn(err.data)
          })
        },


        getScripts(){
          let that = this
          getsqlCompareScript(this.searchScriptDto).then(res=>{
            this.scriptsDtos = res.data.list
            this.page=res.data
          }).catch(err=>{
            that.warn(err.data)
          })
        },

        getProjects(){
          getProject().then(res=>{
            this.projects = res.data
          }).catch(err=>{
            this.warn(err.data)
          })
        },
        warn(message) {
          this.$alert(message, '标题名称', {
            confirmButtonText: '确定',
            callback: action => {
              this.$message({
                type: 'info',
                message: `action: ${ action }`
              });
            }
          });
        },

      },
      mounted(){

        this.getProjects(),
          this.getScripts(),
          this.getUploadUrl(),
          this.getDbs()

      },
      components:{
        selectTool,
        projectTree,
        mytag,
        batchTaskCreate
      },
    }
</script>

<style scoped>
  .set-eltree-textsize >>> .el-tree-node__label {
    font-size: 20px;
  }


  .set-aside >>>  .el-aside {
    padding: 20px;
    overflow: auto;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    -ms-flex-negative: 0;
    flex-shrink: 0;
    padding-top: 40px;
  }
.setbutton >>> .el-button+.el-button {
  margin-left:0px
}
</style>
